const {mysql} = require('../qcloud')

async function addCart (ctx) {
    const {goodsId, openId, count} = ctx.request.body

    if (goodsId && openId) {
        const goods = await mysql('nideshop_cart')
            .where({
                'open_id': openId,
                'goods_id': goodsId
            }).select()

        if (goods.length) {
            try {
                await mysql('nideshop_cart')
                    .where({
                        'open_id': openId,
                        'goods_id': goodsId
                    }).increment('count', count)
                ctx.state.data = {
                    msg: '添加购物车成功',
                    state: false
                }
            } catch (e) {
                ctx.state = {
                    code: -1,
                    data: {
                        msg: `添加购物车失败${e.sqlMessag}1`
                    }
                }
            }
            return
        }

        try {
            await mysql('nideshop_cart').insert({
                'open_id': openId,
                'goods_id': goodsId,
                'count': count
            })

            ctx.state.data = {
                msg: '添加购物车成功',
                state: true
            }
        } catch (e) {
            ctx.state = {
                code: -1,
                data: {
                    msg: `添加购物车失败${e.sqlMessag}2`
                }
            }
        }
    } else {
        console.log('获取客户端发送参数失败')
    }
}

async function cartData (ctx) {
    const {openId} = ctx.request.body

    const cartData = await mysql('nideshop_goods')
        .join('nideshop_cart', 'nideshop_goods.id', '=', 'nideshop_cart.goods_id')
        .where({'open_id': openId})
        .select('nideshop_goods.id', 'nideshop_goods.name', 'nideshop_goods.retail_price', 'nideshop_goods.list_pic_url', 'nideshop_cart.count')

    ctx.state.data = {
        cartData
    }
}

async function deleteGoods (ctx) {
    const {id} = ctx.request.body
    try {
        await mysql('nideshop_cart').where((builder) => builder.whereIn('goods_id', id)).del()
        ctx.state.data = {
            msg: '删除成功'
        }
    } catch (e) {
        ctx.state = {
            code: -1,
            data: {
                msg: `删除失败${e.sqlMessag}`
            }
        }
    }
}

module.exports = {
    cartData,
    addCart,
    deleteGoods
}
